package com.munichosica.myapp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.munichosica.myapp.dao.RolDao;
import com.munichosica.myapp.dto.Rol;
import com.munichosica.myapp.exceptions.RolException;

public class RolDaoImpl implements RolDao{

	private StringBuilder sql;
	
	@Override
	public List<Rol> listarTodo() throws RolException {
		sql=new StringBuilder();
		sql.append("SELECT ROLCODIGO_I AS CODIGO," +
				"ROLNOMBRE_V AS ROL " +
				"FROM ROL");
		
		List<Rol> list=null;
		PreparedStatement stmt=null;
		Connection conn=null;
		ResultSet rs=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sql.toString());
			boolean result=stmt.execute();
			if(result){
				list=new ArrayList<Rol>();
				rs=stmt.getResultSet();
				Rol rol=null;
				while(rs.next()){
					rol=new Rol();
					rol.setRolcodigoI(rs.getInt("CODIGO"));
					rol.setRolnombreV(rs.getString("ROL"));
					list.add(rol);
				}
			}
		} catch (SQLException e) {
			throw new RolException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return list;
	}
	
	public Rol obtener(int codigo) throws RolException{
		sql=new StringBuilder();
		sql.append("SELECT ROLCODIGO_I AS CODIGO," +
				"ROLNOMBRE_V AS ROL " +
				"FROM ROL WHERE ROLCODIGO_I=?");
		PreparedStatement stmt=null;
		Connection conn=null;
		ResultSet rs=null;
		Rol rol=null;
		try {
			conn=ResourceManager.getConnection();
			stmt=conn.prepareStatement(sql.toString());
			stmt.setInt(1, codigo);
			boolean result=stmt.execute();
			if(result){
				rs=stmt.getResultSet();
				if(rs.next()){
					rol=new Rol();
					rol.setRolcodigoI(rs.getInt("CODIGO"));
					rol.setRolnombreV(rs.getString("ROL"));
				}
			}
		} catch (SQLException e) {
			throw new RolException(e.getMessage(),e);
		} finally{
			ResourceManager.close(rs);
			ResourceManager.close(stmt);
			ResourceManager.close(conn);
		}
		return rol;
	}

}
